package com.course.server.service;

import com.course.server.dto.CategoryDto;
import com.course.server.dto.CourseCategoryDto;
import com.course.server.entity.CourseCategory;
import com.course.server.entity.CourseCategoryExample;
import com.course.server.mapper.CourseCategoryMapper;
import com.course.server.util.CopyUtil;
import com.course.server.util.UuidUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: Durian
 * @date: 2021/4/18 18:26
 */
@Service
public class CourseCategoryService {

    @Resource
    private CourseCategoryMapper courseCategoryMapper;

    public List<CourseCategoryDto> listBYCourseId(String courseId) {
        CourseCategoryExample example = new CourseCategoryExample();
        // criteria只能一次
        example.createCriteria().andCourseIdEqualTo(courseId);
        List<CourseCategory> courseCategories = courseCategoryMapper.selectByExample(example);
        return CopyUtil.copyList(courseCategories, CourseCategoryDto.class);
    }

    @Transactional(rollbackFor = {Exception.class})
    public void batchSave(String courseId, List<CategoryDto> categoryDtos) {
        CourseCategoryExample example = new CourseCategoryExample();
        example.createCriteria().andCourseIdEqualTo(courseId);
        courseCategoryMapper.deleteByExample(example);
        categoryDtos.forEach(c -> {
            // category数据转换为CourseCategory
            CourseCategory courseCategory = new CourseCategory();
            courseCategory.setId(UuidUtils.getShortUuid());
            courseCategory.setCategoryId(c.getId());
            courseCategory.setCourseId(courseId);
            insert(courseCategory);
        });
    }

    public void delete(String id) {
        courseCategoryMapper.deleteByPrimaryKey(id);
    }

    private void insert(CourseCategory courseCategory) {
        courseCategory.setId(UuidUtils.getShortUuid());
        courseCategoryMapper.insert(courseCategory);
    }

}
